<script setup lang="ts">
import { reactive, ref, onMounted, watch } from "vue";
import type { FormInstance, FormRules } from "element-plus";
import { Search } from "@element-plus/icons-vue";
import { router } from "@/router";
import { get_scan_tactics } from "@/api/tactics";
import { add_schedule, search_schedule } from "@/api/task";
import { message } from "@/utils/message";

import GatherSix from "../../gather/gathersix.vue";
import { transGMTToBeijing } from "@/utils/regUtil";
import dayjs from "dayjs";

import { originEveryWeekDay, originEveryMonthDays } from "./data";

defineOptions({
  name: "",
});
const formInline = reactive({
  policy_name: "",
  taskName: "",
  creater: "",
  createTime: "",
});

const formAddHardware = reactive({
  taskType: "",
  taskName: "",
  taskRegion: "",
  startTime: "", //启动时间
  linkTactics: "", //关联策略
  cron: "", //cron表达式
  monthDay: "",
  weekDay: "",
});

const addTaskFormRef = ref<FormInstance>();

const hardwareRules = reactive<FormRules>({
  taskName: [
    { required: true, message: "请输入任务名称", trigger: "blur" },
    // { min: 3, max: 5, message: "Length should be 3 to 5", trigger: "blur" }
    // { validator: validatePass2, trigger: 'blur' }
  ],
  taskRegion: [
    {
      required: true,
      message: "请填写资产范围~",
      trigger: "blur",
    },
  ],
  taskType: [
    {
      required: true,
      message: "请选择一个任务类别",
      trigger: "change",
    },
  ],
  linkTactics: [
    {
      required: true,
      message: "请关联策略",
      trigger: "change",
    },
  ],
  startTime: [
    {
      // type: "array",
      required: true,
      message: "请选择日期区间",
      trigger: "change",
      // fields: {
      //   // tpye类型试情况而定,所以如果返回的是date就改成date,如果返回的是string就改成string
      //   0: { type: "date", required: true, message: "请选择开始日期" },
      //   1: { type: "date", required: true, message: "请选择结束日期" }
      // }
    },
  ],
});

const showAddHardwareDialog = ref(false);

//定时任务开始时间
const tiemValue2 = ref("");

//时分秒
const timehhss = ref("");

//展示时分秒
const timehhssShow = ref(false);

//周期类型
const cycleType = ref("");
const everyWeekDay = ref(originEveryWeekDay);
const everyMonthDays = ref(originEveryMonthDays);

const tableData = ref([]);

const tacticsList = ref([]);

//任务类别改变
const taskTypeChange = (params) => {
  tiemValue2.value = "";
  timehhss.value = "";
  cycleType.value = "";
  timehhssShow.value = false;
  formAddHardware.monthDay = "";
  formAddHardware.weekDay = "";
};

const everyMonthDayChange = (params) => {
  timehhssShow.value = true;
  timehhss.value = "00:00";
};

const everyWeekDayChange = () => {
  timehhssShow.value = true;
  timehhss.value = "00:00";
};

const disabledDate = (time) => {
  return time.getTime() < Date.now() - 8.64e7;
};

const getDisabledHours = () => {
  const currentHour = new Date().getHours();
  return Array.from({ length: currentHour }, (_, index) => index);
};

const disabledMinutes = () => {
  const currentMinute = new Date().getMinutes();
  return Array.from({ length: currentMinute + 1 }, (_, index) => index);
};

//0 0 2 1 * ?
const transMonthTypeCron = () => {
  const houerAndMinist = timehhss.value.split(":");
  const monthDay = formAddHardware.monthDay;
  // return `${houerAndMinist[1]} ${houerAndMinist[0]} ${monthDay} * ?`;
  return `${houerAndMinist[1]} ${houerAndMinist[0]} ${monthDay} * *`;
};

const transWeekTypeCron = () => {
  const houerAndMinist = timehhss.value.split(":");
  const weekDay = formAddHardware.weekDay;
  // return `${houerAndMinist[1]} ${houerAndMinist[0]} ? * ${weekDay}`;
  return `${houerAndMinist[1]} ${houerAndMinist[0]} * * ${weekDay}`;
};

//0 0 10 * * ?
const transDayTypeCron = () => {
  const houerAndMinist = timehhss.value.split(":");
  return `${houerAndMinist[1]} ${houerAndMinist[0]} * * *`;
};

//最终转化cron表达式
const transCronOver = () => {
  let cron = ``;
  if (cycleType.value === "month") {
    cron = transMonthTypeCron();
  }
  if (cycleType.value === "week") {
    cron = transWeekTypeCron();
  }

  if (cycleType.value === "day") {
    cron = transDayTypeCron();
  }
  debugger;
  return cron;
};

const getScanTacticsList = () => {
  get_scan_tactics({
    poc_policy_name: "",
    poc_policy_description: "",
    create_user: "",
    scan_policy_id: "",
  })
    .then((result) => {
      if (result.code === 2000) {
        console.log(result);
        tacticsList.value = result.data.policies;
      }
    })
    .catch((err) => {});
};

const addTask = (formEl) => {
  if (!formEl) return;

  //startTime隐藏时的校验问题
  formEl.validate((valid, fields) => {
    if (valid) {
      if (formAddHardware.taskType === "cycle") {
        if (cycleType.value === "") {
          message("请选择周期类型", { type: "error" });
          return;
        }

        if (cycleType.value === "month" && formAddHardware.monthDay === "") {
          message("请选择日期", { type: "error" });
          return;
        }

        if (
          cycleType.value === "month" &&
          formAddHardware.monthDay !== "" &&
          timehhss.value === ""
        ) {
          message("请选择时间", { type: "error" });
          return;
        }

        if (cycleType.value === "week" && formAddHardware.weekDay === "") {
          message("请选择每周几进行扫描", { type: "error" });
          return;
        }

        if (
          cycleType.value === "week" &&
          formAddHardware.weekDay !== "" &&
          timehhss.value === ""
        ) {
          message("请选择时间", { type: "error" });
          return;
        }
      } else {
        console.log(formAddHardware.startTime.getTime());
        if (formAddHardware.startTime.getTime() < Date.now()) {
          message("启动时间不能小于当前时间", { type: "error" });
          return;
        }
      }

      // recurrent_scan
      // future_scan
      debugger;
      addTaskEnd();
    } else {
      return;
    }
  });
};

const transGMTToCurrent = (val) => {
  return dayjs(val).format("YYYY-MM-DD HH:mm:ss");
};

const addTaskEnd = () => {
  const param = {
    name: formAddHardware.taskName,
    target: formAddHardware.taskRegion,
    schedule_type:
      formAddHardware.taskType === "settime" ? "future_scan" : "recurrent_scan",
    scan_policy_id: formAddHardware.linkTactics,
    start_date:
      formAddHardware.taskType === "settime"
        ? transGMTToCurrent(formAddHardware.startTime)
        : "",
    // task_tag: "risk cruising",
    cron: formAddHardware.taskType === "settime" ? "" : transCronOver(),
  };

  debugger;
  add_schedule(param)
    .then((result) => {
      if (result.code === 2000) {
        showAddHardwareDialog.value = false;
        searchTask();
      } else {
        message(result.message, { type: "error" });
      }
    })
    .catch((err) => {});
};

const searchTask = (params) => {
  search_schedule({
    name: formInline.taskName,
    create_user: formInline.creater,
    target: formInline.ipscope,
    scan_police_id: "",
    policy_name: formInline.policy_name,
    status: "",
  })
    .then((result) => {
      if (result.code === 2000) {
        tableData.value = result.data;
      }
    })
    .catch((err) => {});
};

//把cron表达式转化成当前时间
function parseCronCurren(cron) {
  const parts = cron.split(" ");
  // const seconds = parts[0];
  // const minutes = parts[1];
  // const hours = parts[2];
  // const dayOfMonth = parts[3] === "?" ? "*" : parts[3];
  // const month = parts[4] === "?" ? "*" : parts[4];
  // const dayOfWeek = parts[5] === "?" ? "*" : parts[5];

  const seconds = "00";
  const minutes = parts[0];
  const hours = parts[1];
  const dayOfMonth = parts[2] === "?" ? "*" : parts[2];
  const month = parts[3] === "?" ? "*" : parts[3];
  const dayOfWeek = parts[4] === "?" ? "*" : parts[4];

  let result = "";

  if (dayOfWeek === "*" && dayOfMonth === "*") {
    result += "每天";
  } else if (dayOfWeek !== "*" && dayOfMonth !== "*") {
    const days = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"];
    result += "每" + days[dayOfWeek] + "或每月的第" + dayOfMonth + "天 ";
  } else if (dayOfWeek !== "*") {
    const days = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"];
    result += "每" + days[dayOfWeek] + " ";
  } else if (dayOfMonth !== "*") {
    result += "每月的第" + dayOfMonth + "天 ";
  }

  if (month !== "*") {
    result += "的第" + month + "月 ";
  }

  if (hours !== "*") {
    result += hours + "点";
  }

  if (minutes !== "*") {
    result += minutes + "分";
  }

  // if (seconds !== "*") {
  //   result += seconds + "秒";
  // }

  // debugger;

  return result.trim();
}

const resetAddTaskForm = () => {
  formAddHardware.taskType = "";
  formAddHardware.taskName = "";
  formAddHardware.taskRegion = "";
  formAddHardware.startTime = "";
  formAddHardware.linkTactics = "";
  formAddHardware.cron = "";
  formAddHardware.monthDay = "";
  formAddHardware.weekDay = "";
  tiemValue2.value = "";
  timehhss.value = "";
  cycleType.value = "";
  timehhssShow.value = false;
};

const cycleChange = () => {
  if (cycleType.value === "day") {
    timehhssShow.value = true;
  }
};

watch(showAddHardwareDialog, (newVal, oldVal) => {
  resetAddTaskForm();
});

onMounted(() => {
  searchTask();
  getScanTacticsList();
});
</script>

<template>
  <div>
    <div class="gather-container">
      <GatherSix class="gather-box-success" />
    </div>

    <div class="">
      <el-card shadow="never">
        <template #header>
          <div class="card-header">
            <el-form
              :inline="true"
              :model="formInline"
              size="small"
              class="demo-form-inline"
              @submit.prevent
            >
              <el-form-item>
                <el-button type="primary" @click="showAddHardwareDialog = true"
                  >新建任务</el-button
                >
              </el-form-item>

              <el-form-item label="任务名称">
                <el-input
                  v-model="formInline.taskName"
                  placeholder="任务名称"
                  maxlength="30"
                  clearable
                >
                  <template #append>
                    <el-button :icon="Search" />
                  </template>
                </el-input>
              </el-form-item>

              <el-form-item label="创建人">
                <el-input
                  v-model="formInline.creater"
                  placeholder="创建人"
                  maxlength="30"
                  clearable
                >
                  <template #append>
                    <el-button :icon="Search" />
                  </template>
                </el-input>
              </el-form-item>

              <el-form-item label="目标">
                <el-input
                  v-model="formInline.ipscope"
                  placeholder="目标"
                  maxlength="30"
                  clearable
                >
                  <template #append>
                    <el-button :icon="Search" />
                  </template>
                </el-input>
              </el-form-item>

              <el-form-item label="策略名称">
                <el-input
                  v-model="formInline.policy_name"
                  placeholder="策略名称"
                  maxlength="30"
                  clearable
                >
                  <template #append>
                    <el-button :icon="Search" />
                  </template>
                </el-input>
              </el-form-item>
            </el-form>
          </div>
        </template>

        <!-- <div class="ip-chart-box">
        <IpChart :chartDatas="tableData" />
      </div> -->

        <el-table :data="tableData" style="width: 100%">
          <el-table-column type="index" width="100" label="序号" />

          <el-table-column label="任务名称" prop="name" />
          <el-table-column label="类型">
            <template #default="rowscope">
              <span>{{
                rowscope.row.schedule_type === "future_scan"
                  ? "定时任务"
                  : "周期任务"
              }}</span>
            </template>
          </el-table-column>
          <el-table-column label="状态" prop="status">
            <template #default="rowscope">
              <span>扫描中</span>
            </template>
          </el-table-column>
          <el-table-column label="创建人" prop="create_user" />
          <el-table-column label="策略" prop="policy_name" />
          <el-table-column label="配置时间">
            <template #default="rowscope">
              <span v-if="rowscope.row.schedule_type !== 'recurrent_scan'">
                {{ transGMTToCurrent(rowscope.row.start_date) }}</span
              >
              <span v-if="rowscope.row.schedule_type === 'recurrent_scan'">{{
                parseCronCurren(rowscope.row.cron)
              }}</span>
            </template>
          </el-table-column>
          <el-table-column label="上次运行时间" prop="last_run_date" />
          <el-table-column label="下次运行时间" prop="next_run_date" />
          <el-table-column label="操作">
            <template #default="rowscope">
              <el-button
                size="small"
                type="warning"
                disabled
                @click="deleteAsset(rowscope.$index, rowscope.row)"
              >
                删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-card>

      <el-dialog
        v-model="showAddHardwareDialog"
        :show-close="true"
        destroy-on-close
        width="500px"
      >
        <template #header="{ titleId, titleClass }">
          <div class="my-header">
            <h4 :id="titleId" :class="titleClass">新建任务</h4>
          </div>
        </template>

        <el-form
          :inline="false"
          :model="formAddHardware"
          :rules="hardwareRules"
          ref="addTaskFormRef"
          class="demo-form-inline"
        >
          <el-form-item label="任务名称" label-width="100px" prop="taskName">
            <el-input
              v-model="formAddHardware.taskName"
              placeholder="任务名称"
              clearable
              class="min-w-input"
              maxlength="30"
            />
          </el-form-item>

          <el-form-item label="扫描目标" label-width="100px" prop="taskRegion">
            <el-input
              v-model="formAddHardware.taskRegion"
              placeholder="请输入域名, 如baidu.com, live.qq.com, 输入多个目标用换行或逗号分隔!"
              class="min-w-input"
              type="textarea"
              :autosize="{ minRows: 2, maxRows: 5 }"
              clearable
            />
          </el-form-item>

          <el-form-item label="计划类型" label-width="100px" prop="taskType">
            <el-select
              v-model="formAddHardware.taskType"
              placeholder="计划类型"
              class="min-w-input"
              @change="taskTypeChange"
              clearable
            >
              <el-option label="定时任务" value="settime" />
              <el-option label="周期任务" value="cycle" />
            </el-select>
          </el-form-item>
          <!-- :shortcuts="shortcuts" -->
          <el-form-item
            label="启动时间"
            label-width="100px"
            v-if="formAddHardware.taskType === 'settime'"
            prop="startTime"
          >
            <el-date-picker
              v-model="formAddHardware.startTime"
              :disabled-date="disabledDate"
              :disabled-hours="getDisabledHours"
              :disabled-minutes="disabledMinutes"
              type="datetime"
              class="min-w-input"
              @change="changeDate"
            />
          </el-form-item>

          <el-form-item
            label="周期"
            label-width="100px"
            v-if="formAddHardware.taskType === 'cycle'"
          >
            <el-radio-group v-model="cycleType" @change="cycleChange">
              <el-radio label="month">月</el-radio>
              <el-radio label="week">周</el-radio>
              <el-radio label="day">日</el-radio>
              <!-- <el-radio label="周">周</el-radio> -->
            </el-radio-group>
          </el-form-item>

          <el-form-item
            label="日期"
            label-width="100px"
            prop="monthDay"
            v-if="cycleType === 'month'"
          >
            <el-select
              v-model="formAddHardware.monthDay"
              placeholder="日期"
              class="min-w-input"
              @change="everyMonthDayChange"
              clearable
            >
              <el-option
                :label="item.label"
                :value="item.value"
                :key="index"
                v-for="(item, index) in everyMonthDays"
              />
            </el-select>
          </el-form-item>

          <el-form-item
            label="周几"
            label-width="100px"
            prop="weekDay"
            v-if="cycleType === 'week'"
          >
            <el-select
              v-model="formAddHardware.weekDay"
              placeholder="周几"
              class="min-w-input"
              @change="everyWeekDayChange"
              clearable
            >
              <el-option
                :label="item.label"
                :value="item.value"
                :key="index"
                v-for="(item, index) in everyWeekDay"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="时分秒" label-width="100px" v-if="timehhssShow">
            <el-time-picker
              v-model="timehhss"
              value-format="HH:mm"
              format="HH:mm"
              class="min-w-input"
              splaceholder="请选择"
            />
          </el-form-item>

          <el-form-item label-width="100px" v-if="timehhssShow">
            <span v-if="cycleType === 'month'">
              {{
                `将在每月【${formAddHardware.monthDay}】号---${timehhss}进行扫描`
              }}</span
            >
            <span v-if="cycleType === 'week'">
              {{
                `将在每周周【${formAddHardware.weekDay}】---${timehhss}进行扫描`
              }}</span
            >

            <span v-if="cycleType === 'day'">
              {{ `将在每天---${timehhss}进行扫描` }}</span
            >
          </el-form-item>

          <el-form-item label="策略" label-width="100px" prop="linkTactics">
            <el-select
              v-model="formAddHardware.linkTactics"
              placeholder="策略"
              class="min-w-input"
              clearable
            >
              <el-option
                :label="item.poc_policy_name"
                :value="item.scan_policy_id"
                :key="index"
                v-for="(item, index) in tacticsList"
              />
            </el-select>
          </el-form-item>
        </el-form>

        <template #footer>
          <div>
            <el-button @click="showAddHardwareDialog = false"> 取消 </el-button>
            <el-button type="primary" @click="addTask(addTaskFormRef)">
              <!-- <el-icon class="el-icon--left"><CircleCloseFilled /></el-icon> -->
              确认
            </el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<style lang="scss" scoped>
:deep(.el-card__header) {
}
.gather-container {
  display: block;
  margin-bottom: 10px;
}

.min-w-input {
  width: 300px;
}
</style>
